<template>
  <div>
    <q-form class="dialog_card column" ref="editRef">
      <div class="row q-col-gutter-x-md dialog_form q-pa-md">
        <div class="col-12">
          <h5>
            <q-icon color="red" name="star" />
            分类名称：
          </h5>
          <q-input
            :rules="[(val) => (val && val.length > 0) || '请输入分类名称']"
            clearable
            dense
            lazy-rules
            outlined
            type="text"
            v-model="form.cat_name"
          />
        </div>
        <div class="col-12">
          <h5>
            <q-icon color="red" name="star" />
            请选择父级：
          </h5>
          <q-select
            :options="list"
            :rules="[(val) => val !== null || '请选择父类']"
            dense
            emit-value
            map-options
            option-label="symbol_name"
            option-value="cat_id"
            outlined
            v-model="form.parent_id"
          >
          </q-select>
        </div>
        <div class="col-12">
          <h5>图片：</h5>
          <q-btn @click="importImage" round>
            <q-avatar size="100px">
              <q-img
                :src="imagePath(form.image)"
                style="width: 100px; height: 100px"
              ></q-img>
            </q-avatar>
            <yq-uploader
              @uploadedAvatar="uploadedImage"
              ref="yqupload"
            ></yq-uploader>
          </q-btn>
        </div>
        <div class="col-12">
          <h5>是否显示：</h5>
          <q-toggle
            :false-value="0"
            :true-value="1"
            color="bule"
            v-model="form.is_show"
          />
        </div>
        <div class="col-12">
          <h5>状态：</h5>
          <q-toggle
            :false-value="0"
            :true-value="1"
            color="bule"
            v-model="form.cat_state"
          />
        </div>
        <div class="col-12">
          <h5>
            <q-icon color="red" name="star" />
            排序：
          </h5>
          <q-input
            :rules="[(val) => (val && val > 0) || '请输入大于0的排序']"
            clearable
            dense
            lazy-rules
            outlined
            type="number"
            v-model.number="form.cat_sort"
          />
        </div>
      </div>
    </q-form>
  </div>
</template>

<script lang="ts" setup>
import emitter from '@/components/eventbus';
import { categoryAdd, categoryEdit, categoryAll } from '@/api/goods';
import { useQuasar } from 'quasar';

interface Props {
  form: {
    cat_id?: string;
    cat_name?: string;
    image?: string;
    cat_sort?: number;
    cat_state?: number;
    is_show?: number;
    parent_id?: number;
  };
}

const props = withDefaults(defineProps<Props>(), {
  form: () => ({}),
});
const editRef = ref();
const $q = useQuasar();
const yqupload = ref();
const list: any = ref([]);

//上传图片
const importImage = () => {
  yqupload.value.importAvatar();
  // avatarUploader.value.pickFiles();
};

//上传图片回调
const uploadedImage = (xhr: any) => {
  const response = JSON.parse(xhr.xhr.responseText);
  if (response.code == 200) {
    form.value.image = `${process.env.VUE_APP_API_URL}` + response.data.path;
  } else {
    $q.notify({
      color: 'white',
      textColor: 'negative',
      icon: 'cancel',
      position: 'top',
      message: response.msg,
    });
  }
  //清空
  yqupload.value.removeUpload();
};

//接收兄弟组件传递事件
emitter.on('saveData', async () => {
  console.log('saveDatasaveData');
  IsValidate();
});
//表单验证
const IsValidate = () => {
  if (editRef.value) {
    editRef.value.validate().then(async function (validate: any) {
      if (validate) {
        onSubmit();
      } else {
      }
    });
  }
};
//提交数据
const onSubmit = async () => {
  if (form.value.cat_id) {
    const res: any = await categoryEdit(form.value);
    info(res);
  } else {
    const res: any = await categoryAdd(form.value);
    info(res);
  }
};
//信息返回
const info = (res: any) => {
  if (res.code == 200) {
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: res.msg,
    });
    emit('backList');
  }
};

const emit = defineEmits(['update:form', 'backList']);

const form: any = computed({
  set(value: any) {
    // emit('update:form', value);
  },
  get() {
    return props.form;
  },
});

const getAll = async () => {
  const res: any = await categoryAll();
  let data: any = [{ cat_id: 0, symbol_name: '顶级' }];
  res.data.forEach((row: any) => {
    if (row.cat_id != props.form.cat_id && row.parent_id != props.form.cat_id) {
      data.push(row);
    }
  });
  list.value = data;
};

getAll();

const imagePath = (src: any) => {
  let path = '';
  if (src) {
    if (src.startsWith('http') || src.startsWith('https')) {
      return src;
    }
    path = `${process.env.VUE_APP_API_URL}/${src}`;
  }
  return path;
};
</script>
<style lang="scss" scoped></style>
